<?php
/**
 * Writes AJAX XML response conforming to JSF AJAX schema
 * http://java.sun.com/xml/ns/javaee/web-partialresponse_2_0.xsd
 * 
 * @author jan
 */
class AjaxXmlResponseBuilder {
	
	public function sendHeaders() {
		header('Content-Type: text/xml');
		return $this;
	}
	
	public function documentOpen() {
		echo '<?xml version="1.0" encoding="UTF-8" ?><partial-response>';
		return $this;
	}
	public function documentClose() {
		echo '</partial-response>';
		return $this;
	}
	
	public function changesOpen() {
		echo '<changes>';
		return $this;
	}
	public function changesClose() {
		echo '</changes>';
		return $this;
	}
	
	public function updateOpen($id) {
		echo '<update id="' . $id . '"><![CDATA[';
		return $this;
	}
	public function updateClose() {
		echo ']]></update>';
		return $this;
	}
	
	public function update($id, $data) {
		$this->updateOpen($id)->write($data)->updateClose();
		return $this;
	}
	
	public function updateView($id, $viewObject) {
		$this->updateOpen($id);
		$viewObject->render(TRUE);
		$this->updateClose();
		return $this;
	}
	
	public function write($data) {
		echo $data;
		return $this;
	}
	
	public function redirect($url) {
		echo '<redirect url="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"></redirect>';
		return $this;
	}
	
	public static function sendUpdate($id, $data) {
		$builder = new AjaxXmlResponseBuilder();
		$builder->documentOpen();
		$builder->updateOpen($id);
		$builder->write($data);
		$builder->updateClose();
		$builder->documentClose();
	}
}
